package Offer;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 序列化二叉树
 * @author 是阿秋啊
 * @date 2022/08/17 15:42
 **/
public class Num37 {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null) return "[]";
        StringBuilder sb = new StringBuilder("[");
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(node != null){
                sb.append(node.val + ",");
                queue.offer(node.left);
                queue.offer(node.right);
            }else{
                sb.append("null,");
            }
        }
        return sb.deleteCharAt(sb.length() - 1).append("]").toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.equals("[]")) return null;
        String[] tmp = data.substring(1,data.length()-1).split(",");
        TreeNode root = new TreeNode(Integer.parseInt(tmp[0]));
        int i = 1;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            if(!"null".equals(tmp[i])){
                TreeNode left = new TreeNode(Integer.parseInt(tmp[i]));
                node.left = left;
                queue.offer(node.left);
            }
            i++;
            if(!"null".equals(tmp[i])){
                TreeNode right = new TreeNode(Integer.parseInt(tmp[i]));
                node.right = right;
                queue.offer(node.right);
            }
            i++;
        }
        return root;
    }
}